package com.samnative.pineapple.widget;

import android.app.ActionBar.LayoutParams;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.samnative.pineapple.entity.ProductQianggouModel;
import com.samnative.pineapple.entity.ProductSkuModel;
import com.samnative.pineapple.entity.ProductSpecModel;
import com.samnative.pineapple.main.R;
import com.samnative.pineapple.utils.GlideRequestOptions;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 商品规格选择POP
 *
 * @author WangPeng
 */
public class ProductStandardPop extends PopupWindow {

    private Context mContext;
    /**
     * 有效区域
     */
    private View viewMenu;
    /**
     * 规格外层
     */
    private LinearLayout linear;
    /**
     * 保存选中的规格下标
     */
    private Map<Integer, Integer> indexsMap;
    /**
     * 规格列表
     */
    private List<ProductSpecModel> listSpec;
    /**
     * SKU列表
     */
    private List<ProductSkuModel> listSku;
    /**
     * 规格图片
     */
    private ImageView ivSpecPic;
    /**
     * SKU单价
     */
    private TextView amount_tv;
    /**
     * SKU库存
     */
    private TextView tvStorage;
    /**
     * 当前选中的SKU
     */
    private ProductSkuModel currentSku;
    /**
     * 数量选择器
     */
    private AddSubtractNumView2 asvn;
    /**
     * 阴影层
     */
    private View viewShade;
    /**
     * 确定
     */
    private TextView tvAdd;
    /**
     * 加入购物车和立即购买按钮
     */
    private TextView btnAddCar, btnNowBuy;
    /**
     * 售罄
     */
    private TextView btnSq;
    /**
     * 回调
     */
    public OnStandrad onStandrad;
    /**
     * 点击确定是添加还是立即购买
     */
    public boolean isNow;
    /**
     * 起购数
     */
    private int minNum = 1;
    /**
     * 活动限购提示
     */
    private TextView tv_hd_xg;
    /**
     * 显示已选规格
     */
    private TextView tv_sku_stand;
    /**
     * 显示限购
     */
    private TextView tv_gmsl;
    /**
     * 浮点数格式化
     */
    private DecimalFormat df = new DecimalFormat("0.00");
    /**
     * 抢购信息
     */
    private ProductQianggouModel qianggouModel;

    public ProductQianggouModel getQianggouModel() {
        return qianggouModel;
    }

    public void setQianggouModel(ProductQianggouModel qianggouModel) {
        this.qianggouModel = qianggouModel;
    }

    /**
     * 送NBTC的信息
     */
    public String nbtctitle;

    public String getNbtctitle() {
        return nbtctitle;
    }

    public void setNbtctitle(String nbtctitle) {
        this.nbtctitle = nbtctitle;
    }

    public void setOnStanDrad(OnStandrad onStandrad) {
        this.onStandrad = onStandrad;
    }

    public interface OnStandrad {
        /**
         * 立即购买
         */
        public void buyNow(ProductSkuModel currentSku, int num);

        /**
         * 添加购物车
         */
        public void addCar(ProductSkuModel currentSku, int num);

        /**
         * 返回选中的规格
         */
        public void getStandrad(ProductSkuModel currentSku, int num,
                                String content);
    }

    public ProductStandardPop(final Context context) {
        this.mContext = context;
        LayoutInflater inflater = LayoutInflater.from(context);
        indexsMap = new HashMap<>();
        qianggouModel = new ProductQianggouModel();
        viewMenu = inflater.inflate(R.layout.pop_product_standard, null);
        viewMenu.findViewById(R.id.pop_close).setOnClickListener(
                new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dismiss();
                    }
                });
        // 点击有效区域外则退出pop
        viewMenu.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int hight = viewMenu.findViewById(R.id.sv_pop_layout).getTop();
                int point = (int) event.getY();
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    if (point < hight) {
                        dismiss();
                    }
                }
                return true;
            }
        });

        tvAdd = (TextView) viewMenu.findViewById(R.id.btn_add);
        tvAdd.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                if (currentSku == null) {
                    ToastUtils.showShort("请选择商品规格");
                    return;
                }

                if (currentSku.getProductstorage() == 0) {
                    ToastUtils.showShort("库存不足!");
                    return;
                }

                if (qianggouModel.getLimitbuy() == 0) {
                    ToastUtils.showShort("该商品不可购买!");
                    return;
                }

                if (qianggouModel.getLimitbuy() != -1 && asvn.getNum() > qianggouModel.getLimitbuy()) {
                    ToastUtils.showShort("超出活动限购数");
                    return;
                }

                if (isNow) {
                    if (onStandrad != null && currentSku != null) {
                        onStandrad.buyNow(currentSku, asvn.getNum());
                    } else {
                        ToastUtils.showShort("请选择商品规格");
                    }
                } else {
                    if (onStandrad != null && currentSku != null) {
                        onStandrad.addCar(currentSku, asvn.getNum());
                    } else {
                        ToastUtils.showShort("请选择商品规格");
                    }
                }

            }
        });

        // 加入购物车
        btnAddCar = (TextView) viewMenu.findViewById(R.id.btn_add_shoppingcar);
        btnAddCar.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                if (currentSku == null) {
                    ToastUtils.showShort("请选择商品规格");
                    return;
                }

                if (currentSku.getProductstorage() == 0) {
                    ToastUtils.showShort("库存不足!");
                    return;
                }

                if (qianggouModel.getLimitbuy() == 0) {
                    ToastUtils.showShort("该商品不可购买!");
                    return;
                }

                if (qianggouModel.getLimitbuy() != -1 && asvn.getNum() > qianggouModel.getLimitbuy()) {
                    ToastUtils.showShort("超出活动限购数");
                    return;
                }

                if (onStandrad != null && currentSku != null) {
                    onStandrad.addCar(currentSku, asvn.getNum());
                } else {
                    ToastUtils.showShort("请选择商品规格");
                }
            }
        });

        // 立即购买
        btnNowBuy = (TextView) viewMenu.findViewById(R.id.btn_buy_now);
        btnNowBuy.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                if (currentSku == null) {
                    ToastUtils.showShort("请选择商品规格");
                    return;
                }

                if (currentSku.getProductstorage() == 0) {
                    ToastUtils.showShort("库存不足!");
                    return;
                }

                if (qianggouModel.getLimitbuy() == 0) {
                    ToastUtils.showShort("该商品不可购买!");
                    return;
                }

                if (qianggouModel.getLimitbuy() != -1 && asvn.getNum() > qianggouModel.getLimitbuy()) {
                    ToastUtils.showShort("超出活动限购数");
                    return;
                }

                if (onStandrad != null && currentSku != null) {
                    onStandrad.buyNow(currentSku, asvn.getNum());
                } else {
                    ToastUtils.showShort("请选择商品规格");
                }
            }
        });

        asvn = (AddSubtractNumView2) viewMenu.findViewById(R.id.asnv_standard);
        asvn.setOnAsnwChecked(new AddSubtractNumView2.OnAsnwChecked() {
            @Override
            public void getNum(int num) {
                setPrice("");
            }
        });
        ivSpecPic = (ImageView) viewMenu.findViewById(R.id.standard_icon);
        amount_tv = (TextView) viewMenu.findViewById(R.id.amount_tv);
        tvStorage = (TextView) viewMenu.findViewById(R.id.tv_sku_storeag);
        linear = (LinearLayout) viewMenu.findViewById(R.id.standard_ll);
        viewShade = viewMenu.findViewById(R.id.v_pop_shade);
        btnSq = (TextView) viewMenu.findViewById(R.id.btn_shouqin);
        tv_hd_xg = (TextView) viewMenu.findViewById(R.id.tv_hd_xg);
        tv_sku_stand = (TextView) viewMenu.findViewById(R.id.tv_sku_stand);
        tv_gmsl = (TextView) viewMenu.findViewById(R.id.tv_gmsl);
        setContentView(viewMenu);
        setWidth(LayoutParams.MATCH_PARENT);
        setHeight(LayoutParams.MATCH_PARENT);
        setFocusable(true);
        setAnimationStyle(R.style.AnimBottom);
        setBackgroundDrawable(new ColorDrawable(0x00000000));
        setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
    }

    @Override
    public void showAtLocation(View parent, int gravity, int x, int y) {
        // TODO Auto-generated method stub
        viewShade.setVisibility(View.GONE);
        super.showAtLocation(parent, gravity, x, y);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                AlphaAnimation anim = new AlphaAnimation(0.0f, 1.0f);
                anim.setDuration(200);
                viewShade.startAnimation(anim);
                viewShade.setVisibility(View.VISIBLE);
            }
        }, 300);

    }

    @Override
    public void dismiss() {
        // TODO Auto-generated method stub
        AlphaAnimation anim = new AlphaAnimation(1.0f, 0.0f);
        anim.setDuration(200);
        anim.setAnimationListener(new AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
                // TODO Auto-generated method stub
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
                // TODO Auto-generated method stub
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                // TODO Auto-generated method stub
                viewShade.setVisibility(View.GONE);
                ProductStandardPop.super.dismiss();
            }
        });
        viewShade.startAnimation(anim);
    }

    /**
     * 设置 规格列表
     *
     * @param listSpec
     */
    public void setData(List<ProductSpecModel> listSpec,
                        List<ProductSkuModel> listSku, String skuID) {
        if (listSku == null || listSku.size() == 0) {
            return;
        }
        currentSku = null;
        this.listSpec = listSpec;
        this.listSku = listSku;

        String spec = "";
        if (skuID == null) {
            skuID = "";
        }
        // 找出默认选中的SKU
        for (int i = 0; i < listSku.size(); i++) {
            if ((listSku.get(i).getId() + "").equals(skuID)) {
                // 找出选中的规格
                spec = listSku.get(i).getF_productspec();
                break;
            }
        }

        String[] specArray = null;
        if (!spec.isEmpty()) {
            specArray = spec.split(",");
        }
        linear.removeAllViews();

        try {
            for (int i = 0; i < listSpec.size(); i++) {
                int position = -1;
                for (int j = 0; j < listSpec.get(i).getValue().size(); j++) {
                    if (specArray != null
                            && (listSpec.get(i).getValue().get(j).getId() + "")
                            .equals(specArray[i])) {
                        position = j;
                    }
                }
                StandardTypeView st = new StandardTypeView(mContext,
                        listSpec.get(i), i, position);
                linear.addView(st);
                indexsMap.put(i, position);
            }

            showCurrentStand();
        } catch (Exception e) {
            e.printStackTrace();
            ToastUtils.showShort("规格解析错误!");
        }

        if (nbtctitle == null || nbtctitle.isEmpty()) {
            tv_hd_xg.setVisibility(View.GONE);
        } else {
            tv_hd_xg.setVisibility(View.VISIBLE);
            tv_hd_xg.setText(nbtctitle);
        }

    }

    /***
     * 设置起购数量
     *
     * @param num
     */
    public void setMinNum(int num) {
        minNum = num;
        asvn.setMinNum(num);
        asvn.setNumDefault(num);
    }

    /**
     * 规格视图
     *
     * @author WangPeng
     */
    class StandardTypeView extends LinearLayout {
        Context context;

        /**
         * 规格名称
         */
        private TextView tvStandar;
        /**
         * 规格元素
         */
        private CustomGridview gridView;
        /**
         * 适配器
         */
        private StandardAdapter adapter;
        /**
         * 规格列表
         */
        private ProductSpecModel specModel;
        /**
         * 当前是第种规格
         */
        private int index;
        /**
         * 默认选中的下标
         */
        private int pos;

        public StandardTypeView(Context context, ProductSpecModel specModel,
                                int index, int pos) {
            super(context);
            // TODO Auto-generated constructor stub
            this.context = context;
            this.specModel = specModel;
            this.index = index;
            this.pos = pos;
            init();

        }

        public StandardTypeView(Context context, AttributeSet attrs) {
            super(context, attrs);
            // TODO Auto-generated constructor stub
            this.context = context;
            init();
        }

        public void init() {

            LayoutInflater.from(context).inflate(
                    R.layout.pop_product_standard_type, this, true);
            tvStandar = (TextView) findViewById(R.id.standard_name);
            tvStandar.setText(specModel.getSpec_name());
            adapter = new StandardAdapter(context, specModel.getValue());
            adapter.setCurrent(pos);
            gridView = (CustomGridview) findViewById(R.id.standard_grid);
            gridView.setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> parent, View view,
                                        int position, long id) {
                    // TODO Auto-generated method stub
                    adapter.setCurrent(position);
                    indexsMap.put(index, position);
                    showCurrentStand();
                }
            });
            gridView.setAdapter(adapter);

        }
    }

    /**
     * 设置按钮显示
     *
     * @param type  0显示两按钮 1显示一按钮
     * @param isnow 为1个按钮时判断 false加入购物车 true立即购买
     */
    public void setBtn(int type, boolean isnow) {
        if (type == 0) {
            btnAddCar.setVisibility(View.VISIBLE);
            btnNowBuy.setVisibility(View.VISIBLE);
            tvAdd.setVisibility(View.GONE);
        } else if (type == 1) {
            btnAddCar.setVisibility(View.GONE);
            btnNowBuy.setVisibility(View.GONE);
            tvAdd.setVisibility(View.VISIBLE);
            this.isNow = isnow;
        }

    }

    /**
     * 设置显示售罄
     *
     * @param tip
     */
    public void setBtnSq(String tip) {
        btnAddCar.setVisibility(View.GONE);
        btnNowBuy.setVisibility(View.GONE);
        tvAdd.setVisibility(View.GONE);
        btnSq.setVisibility(View.VISIBLE);
        btnSq.setText(tip);
    }

    /**
     * 显示当前规格
     */
    public void showCurrentStand() {
        try {
            StringBuilder sbId = new StringBuilder();
            StringBuilder sbName = new StringBuilder();
            for (int i = 0; i < listSpec.size(); i++) {
                int index = indexsMap.get(i);
                if (index >= 0) {
                    sbId.append(listSpec.get(i).getValue().get(index).getId()
                            + "");
                    sbName.append(listSpec.get(i).getValue().get(index)
                            .getSpec_value());
                    if (i < listSpec.size() - 1) {
                        sbId.append(",");
                        sbName.append(" 、");
                    }
                }
            }

            for (int i = 0; i < listSku.size(); i++) {
                if (listSku.get(i).getF_productspec().equals(sbId.toString())) {
                    currentSku = listSku.get(i);

                    int storate = listSku.get(i)
                            .getProductstorage();
                    asvn.setMaxNum(storate);

                    if (qianggouModel.getQianggou_flag() == 1) {

                        if (qianggouModel.getStatus() == 2) {
                            storate = Integer.parseInt(qianggouModel.getProductstorage());
                            asvn.setMaxNum(storate);
                        }

                        if (qianggouModel.getLimitbuy() == -1) {
                            tv_gmsl.setText("");
                        } else if (qianggouModel.getLimitbuy() == 0) {
                            tv_gmsl.setText("超过限购数");
                            asvn.setMaxNum(0);
                        } else {
                            tv_gmsl.setText("限购" + qianggouModel.getLimitbuy() + "件");
                            asvn.setMaxNum(qianggouModel.getLimitbuy());
                        }
                    }

                    if (storate < 10) {
                        tvStorage.setText("仅剩" + storate);
                    } else {
                        tvStorage.setText("库存" + storate);
                    }

                    setPrice("");
                    break;
                }
            }

            if (!sbName.toString().isEmpty()) {
                tv_sku_stand.setText(sbName.toString());
            }

            if (currentSku != null) {
                Glide.with(mContext)
                        .load(currentSku.getProductimage()) //图片地址
                        .apply(GlideRequestOptions.OPTIONS_400_400)
                        .into(ivSpecPic);

                if (onStandrad != null) {
                    onStandrad.getStandrad(currentSku, asvn.getNum(),
                            sbName.toString());
                }
            } else if (listSku.size() > 0) {
                Glide.with(mContext)
                        .load(listSku.get(0).getProductimage()) //图片地址
                        .apply(GlideRequestOptions.OPTIONS_400_400)
                        .into(ivSpecPic);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置当前价格
     */
    public void setPrice(String amount) {
        amount_tv.setText(amount);
        try {
            double price = Double.parseDouble(currentSku.getProuctprice());
            double bull = Double.parseDouble(currentSku.getBullamount());

            if (qianggouModel.getQianggou_flag() == 1 && qianggouModel.getStatus() == 2) {
                price = Double.parseDouble(qianggouModel.getProuctprice());
                bull = Double.parseDouble(qianggouModel.getBullamount());
            }

            if (price > 0 && bull > 0) {
                amount_tv.setText("¥" + df.format(price) + " + " + df.format(bull) + "积分");
            } else if (price > 0 && bull == 0) {
                amount_tv.setText("¥" + df.format(price));
            } else {
                amount_tv.setText(df.format(bull) + "积分");
            }
        } catch (Exception e) {
            // TODO: handle exception
        }

    }

    /**
     * 单个规格元素显示适配器
     *
     * @author WangPeng
     */
    class StandardAdapter extends BaseAdapter {

        private Context context;
        private List<ProductSpecModel.Value> listValue;
        private int currentPosition;

        public StandardAdapter(Context context,
                               List<ProductSpecModel.Value> listValue) {
            this.context = context;
            this.listValue = listValue;
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return listValue.size();
        }

        @Override
        public Object getItem(int arg0) {
            // TODO Auto-generated method stub
            return listValue.get(arg0);
        }

        @Override
        public long getItemId(int arg0) {
            // TODO Auto-generated method stub
            return arg0;
        }

        @Override
        public View getView(int arg0, View view, ViewGroup arg2) {
            viewHolder holder = null;
            if (view == null) {
                holder = new viewHolder();
                view = LayoutInflater.from(context).inflate(
                        R.layout.pop_product_standard_item, null);
                holder.tvStandard = (TextView) view
                        .findViewById(R.id.tv_standard);
                view.setTag(holder);
            } else {
                holder = (viewHolder) view.getTag();
            }

            if (arg0 == currentPosition) {
                holder.tvStandard.setBackgroundResource(R.drawable.btn_red_no);
                holder.tvStandard.setTextColor(context.getResources().getColor(
                        R.color.main_white));
            } else {
                holder.tvStandard.setBackgroundResource(R.drawable.btn_gary_no);
                holder.tvStandard.setTextColor(context.getResources().getColor(
                        R.color.main_tab_text_n));
            }

            holder.tvStandard.setText(listValue.get(arg0).getSpec_value());

            return view;
        }

        public void setCurrent(int current) {
            if (current != currentPosition) {
                currentPosition = current;
                notifyDataSetChanged();
            }
        }

    }

    private static class viewHolder {
        TextView tvStandard;
    }

}
